package com.janlei.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockStu {
    static public Object obj = new Object();
    static public Lock lock = new ReentrantLock();
    static Condition c1 = lock.newCondition();
    static Condition c2 = lock.newCondition();

    /**
     * 线程五态
     * 1 init 初始化new
     * 2 start 可运行状态
     * 3 sleep wait阻塞状态
     * 4 join 执行结束才可往下执行
     * 5 执行结束 死亡状态
     * <p>
     * 如何终止线程 t.interrupt()
     */
    static public void runConcurrent() {
        Thread thread = new Thread(() -> {
            try {
                lock.lock();
                c1.await();
                System.out.println("hello");
                c2.await();
                System.out.println("hello2");
                Thread.sleep(1000);
                while (!Thread.currentThread().isInterrupted()) ;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });
        thread.start();
    }

    static public void runSynchronized() {
        Thread thread = new Thread(() -> {
            synchronized (obj) {
                try {
                    System.out.println("hello");
                    while (!Thread.currentThread().isInterrupted()) ;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        thread.interrupt();
    }

    public static void main(String[] args) throws InterruptedException {
        test1();
    }

    private static void test2() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            runConcurrent();
        }
        Thread.sleep(2000);
        lock.lock();
        c1.signalAll();
        lock.unlock();
        Thread.currentThread().join(100);

        lock.lock();
        c2.signalAll();
        lock.unlock();
    }

    private static void test1() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            runSynchronized();
        }
        Thread.sleep(2000);
        synchronized (obj) {
            obj.notifyAll();
        }
    }
}
